package com.ld.exception;


import com.ld.common.ResultInfoFactory;
import com.ld.emun.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class InspectionGlobalExceptionHandler {
//    @ExceptionHandler(Exception.class)
//    public ResultInfoFactory handler(Exception e, HttpServletRequest request) {
//        log.error("未知异常:{},URI:{}", e, request.getRequestURI());
//        e.printStackTrace();
//        return ResultInfoFactory.failed(ErrorCodeEnum.UNKNOWN_ERROR, Lists.list(e.getMessage()));
//    }

    @ExceptionHandler(ServletRequestBindingException.class)
    public ResultInfoFactory handler() {
        return ResultInfoFactory.failed(ErrorCodeEnum.BIND_EXCEPTION_ERROR);
    }

    @ExceptionHandler(BindException.class)
    public ResultInfoFactory handler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage="";
        if (bindingResult.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                stringBuilder.append(fieldError.getDefaultMessage() + ",");
            }
            errorMessage = stringBuilder.substring(0, stringBuilder.length() - 1);
        }
        return ResultInfoFactory.failed(ErrorCodeEnum.BIND_EXCEPTION_ERROR.getCode(), errorMessage);

    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResultInfoFactory handler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String errorMessage="";
        if (bindingResult.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                stringBuilder.append(fieldError.getDefaultMessage() + ",");
            }
            errorMessage = stringBuilder.substring(0, stringBuilder.length() - 1);
        }
        return ResultInfoFactory.failed(ErrorCodeEnum.BIND_EXCEPTION_ERROR.getCode(), errorMessage);};

    @ExceptionHandler(BusinessException.class)
    public ResultInfoFactory handler(BusinessException e) {
        return ResultInfoFactory.failed(e);
    }
}
